﻿using System;
using System.IO;
using System.ComponentModel;

using Flagwind.Resources;
using Flagwind.Services;

namespace Flagwind.Externals.Storages.Commands
{
	[DisplayName("${Text.Storages.FileUploadCommand.Title}")]
	[Description("${Text.Storages.FileUploadCommand.Description}")]
	[CommandOption(FileUploadCommand.DIRECTORY_OPTION, Type = typeof(string), Required = false, Description = "${Text.FileUploadCommand.Options.Directory}")]
	[CommandOption(FileUploadCommand.NAME_OPTION, Type = typeof(string), Required = true, Description = "${Text.FileUploadCommand.Options.Name}")]
	public class FileUploadCommand : CommandBase<CommandContext>
	{
		#region 常量定义

		private const string DIRECTORY_OPTION = "directory";
		private const string NAME_OPTION = "name";

		#endregion

		#region 成员字段

		private StorageClient _client;

		#endregion

		#region 公共属性

		public StorageClient Client
		{
			get
			{
				return _client;
			}
			set
			{
				if(value == null)
					throw new ArgumentNullException();

				_client = value;
			}
		}

		#endregion

		#region 构造方法

		public FileUploadCommand() : base("Upload")
		{

		}

		#endregion

		#region 重写方法

		protected override object OnExecute(CommandContext context)
		{
			if(context.Expression.Options.Count < 1)
				throw new CommandException(ResourceUtility.GetString("${Text.MissingCommandArguments}"));

			// 获取目录
			var directory = string.Empty;

			context.Expression.Options.TryGetValue(DIRECTORY_OPTION, out directory);

			// 获取原始文件名
			var name = string.Empty;

			if(!context.Expression.Options.TryGetValue(NAME_OPTION, out name))
				throw new CommandException(ResourceUtility.GetString("${Text.MissingCommandArguments}"));

			// 获取文件流
			var stream = context.Parameter as Stream;

			if(stream == null)
				throw new CommandException(ResourceUtility.GetString("${Text.MissingCommandArguments}"));

			// 调用客户端进行上传操作
			var result = TaskHelper.ExecuteTask(() => this.Client.Upload(directory, name, stream));

//			var result = this.Client.Upload(directory, name, stream);

			if(result != null)
				return result.Path.Url;

			return null;
		}

		#endregion
	}
}
